package twentytwenty;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Zahi
 * @Description:
 * @Date Created in 2020-12-15 11:40
 * @Modified By:
 */
public class ThirdMax_414 {
    public static void main(String [] args){
        int [] nums = new int[]{4,3,2,5};
        System.out.println(thirdMax1(nums));
    }

    public static int thirdMax(int [] nums){
        Arrays.sort(nums);
        List<Integer> arr = new ArrayList<>();
        for (int num : nums) {
            if (!arr.contains(num)) {
                arr.add(num);
            }
        }
        if (arr.size() == 1) {
            return nums[0];
        }
        if (arr.size() == 2) {
            return Math.max(arr.get(0), arr.get(1));
        }
        return arr.get(arr.size() - 3);
    }

    public static int thirdMax1(int[] nums) {
        long a1 = (long) Integer.MIN_VALUE - 1;
        long a2 = (long) Integer.MIN_VALUE - 1;
        long a3 = (long) Integer.MIN_VALUE - 1;
        for (int num : nums) {
            if (num > a3 && num != a2 && num != a1) {
                if (num > a2) {
                    if (num > a1) {
                        a3 = a2;
                        a2 = a1;
                        a1 = num;
                    } else {
                        a3 = a2;
                        a2 = num;
                    }
                } else {
                    a3 = num;
                }
            }
        }
        // 如果a3没变，则返回a1
        return (int) (a3 != (long) Integer.MIN_VALUE - 1 ? a3 : a1);
    }
}
